<?php

class ImageHelper extends Helper {

  var $helpers = array("Html");
  
  function getImage($item,$attributes = null){
  //$item could be a category,, subcategory, or product
    $image = null;
    //first, see if there is a product-specific image
    if (isset($item['Product']) and file_exists(WWW_ROOT . IMAGES_URL . 'products/' . $item['Product']['product_id'] . '.jpg')) {
      $image = 'products/' . $item['Product']['product_id'] . '.jpg';
      $link_url = '/../images/' . $image;
    } else if (isset($item['Product']['Subcategory'])) {
      $item['Subcategory'] = $item['Product']['Subcategory'];
    }
    //next, see if there is a sub-category specific image
    if ($image == null and isset($item['Subcategory']) and file_exists(WWW_ROOT . IMAGES_URL . 'subcategories/' . $item['Subcategory']['subcategory_id'] . '.png')) {
      $image = 'subcategories/' . $item['Subcategory']['subcategory_id'] . '.png';
      $link_url = '/subcategories/view/' . $item['Subcategory']['subcategory_id'];
    } else if (!isset($item['Category'])){
      $item['Category'] = $item['Subcategory'];
    }
    //finaly, see if there is a category specific image
    if ($image == null and isset($item['Category']) and file_exists(WWW_ROOT . IMAGES_URL . 'categories/' . $item['Category']['category_id'] . '.png')) {
      $image = 'categories/' . $item['Category']['category_id'] . '.png';
      $link_url = '/categories/view/' . $item['Category']['category_id'];
    }
    //if still null, grab the WM Coop logo
    if ($image == null) {
      $image = 'logo-small.png';
    }
    if (isset($attributes['link'])) {
      $link_url = $attributes['link'];
      unset($attributes['link']);
    }
    $image = $this->Html->image($image,$attributes);
    $ret = (isset($link_url)) ? $this->Html->link($image,$link_url,null,false,false) : $image;
    return $this->output($ret);
  }

}
